package com.zetyun.tiger.connector.format;

import com.zetyun.rt.meta.annotation.ActionMeta;
import com.zetyun.rt.sdk.action.MapAction;
import com.zetyun.rt.sdk.model.RtEvent;
import com.zetyun.rt.sdk.operator.OperatorContext;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@ActionMeta(
        id = "tiger.format-attr-promotion",
        tags = {"redis"},
        category = "sink",
        name = "AttrPromotionAction",
        description = "自定义属性提升",
        parameterClass = AttrPromotionParameter.class,
        status = ActionMeta.Status.PUBLIC
)
@Slf4j
public class AttrPromotionAction extends MapAction {


    private AttrPromotionParameter param;

    private List<AttrPromotionBean> attrs;

    @Override
    public void init(OperatorContext context) {
        super.init(context);
        param = context.getParameters();
        attrs = param.getAttrs();
    }


    @Override
    public RtEvent apply(RtEvent in) throws Exception {
        for (AttrPromotionBean attr : attrs) {
            String mapFieldName = attr.getMapFieldName();
            String keyFieldName = attr.getKeyFieldName();
            String resFieldName = attr.getResFieldName();
            Boolean enableDel = attr.getEnableDel();
            Map<String, Object> mapVal = in.getField(mapFieldName, Map.class);
            if (mapVal == null) {
                in.setValue(resFieldName, "");
                continue;
            }
            if (keyFieldName != null && !keyFieldName.isEmpty()) {
                Object keVal = mapVal.get(keyFieldName);
                in.setValue(resFieldName, keVal);
            } else {
                in.setValue(resFieldName, mapVal);
            }
            if (enableDel) {
                in.removeField(mapFieldName);
            }
        }

        return in;
    }
}
